//
//  ComposeViewController.swift
//  微博项目
//
//  Created by zhaoyinpeng on 16/3/16.
//  Copyright © 2016年 zhaoyinpeng. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    
    @objc private func selectPicture() {
        print("选择图片")
        //.跟新布局
        UIView.animateWithDuration(0.25) { () -> Void in
           self.pictureSelectorVC.view.snp_updateConstraints(closure: { (make) -> Void in
            make.height.equalTo(ScreenHeight / 3 * 2)

           })
            
            //.强制刷新页面
            self.view.layoutIfNeeded()
            
        }
    }
    
    @objc private func selectEmoticon() {
        print("选择表情")
    }
    //.关闭页面
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    //.发布微博
    
    @objc private func send() {
        print(__FUNCTION__)
        
        //.查看接口文档
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        
        guard let token = UserAccount.shareAccout.access_token else {
            print("用户未登录 或 账户过期")
            return
        }
        
        let parameters = ["access_token": token,"status":textView.text]
        
        
        if pictureSelectorVC.imageList.count != 0 {
            
        urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            //.将图片转换成 二进制数据
        let imageData = UIImagePNGRepresentation(pictureSelectorVC.imageList.first!)!
            
            //.发布一个带图片的微博
            //.AFN 上传图片的方式
            HTTPClient.sharedHttpClient.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                //.将要上传的文件的二进制数据 拼接到formData 中
                
                for image in self.pictureSelectorVC.imageList {
                    let data = UIImagePNGRepresentation(image)!
                    formData.appendPartWithFileData(data, name: "pic", fileName: "asd", mimeType: "application/octet-stream")
                }
                
                }, progress: nil, success: { (_, result) -> Void in
                    print(result)
                }, failure: { (_, error) -> Void in
                    print(error)
            })
            
            
            } else {
            //.发布文字微博
            HTTPClient.sharedHttpClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("发布微博失败")
                    return
                }
                
                //.发布成功
                SVProgressHUD.showSuccessWithStatus("发布成功")
                self.close()
            }
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
     setupUI()
        
        //.注册通知
        registerNotification()
    }
    
    //.通知的监听方法 会回调通知对象
    @objc private func keyboardChange(n: NSNotification) {
        print(n)
        
        //.更改底部视图的 底部约束
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //.更新约束
        let offset = -ScreenHeight + rect.origin.y
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(offset)
            })
            
            //后刷新视图
            self.view.layoutIfNeeded()
        }
    }
    
    
    //.添加键盘的出现和隐藏通知
    private func registerNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    //.懒加载视图
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.backgroundColor = UIColor.yellowColor()
//        tv.text = "想放就放吧"
        
        tv.font = UIFont.systemFontOfSize(17)
        
        //.设置代理
        tv.delegate = self
        
        //.设置收起键盘的方式
        tv.keyboardDismissMode = .OnDrag
        //.设置键盘垂直方向可以拽动  设置可以滑出边界
        tv.alwaysBounceVertical = true
        
       return tv
    }()
    
    private lazy var placeholderLabel: UILabel = UIFactory.labelFactory(UIColor.lightGrayColor(), fontSize: 17, text: "想放就放吧")
    //.底部工具条  系统默认高度  44
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //图片添加
    private lazy var pictureSelectorVC: PictureSelectorController = PictureSelectorController()
}


extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
//        print(textView.text)
        //.当输入文字 隐藏占位文本
        placeholderLabel.hidden = textView.hasText()
        
        //设置 ‘发布’按钮的交互，有文字就可以交互
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
}


//.MARK: 跟新UI
extension ComposeViewController {
    
    private func setupUI() {
        
        //.设置背景色
        view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        //.设置输入视图
        setTextView()
        
        
        setPicturSelectorVC()
        //.设置底部工具条
        setToolBar()
    }
    
    
    //.设置图片添加器
    private func setPicturSelectorVC() {
        
        self.addChildViewController(pictureSelectorVC)
        
        self.view.addSubview(pictureSelectorVC.view)
        
        //.设置约束
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
            
        }
        
    }
    
    //.设置底部工具条
    private func setToolBar() {
        
        view.addSubview(toolBar)
        
        //.设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(self.view)
        }
        
        
        var items = [UIBarButtonItem]()
        
        //添加 UIBarButtonItem类型的对象到数据源数组中
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
            let imageName = item["imageName"]
            let btn = UIFactory.buttonWithImage(imageName, backImageName: nil)
            if let actionName = item["actionName"] {
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            let barItem = UIBarButtonItem(customView: btn)
            //.添加到数组中
            items.append(barItem)
            
            //.添加弹簧类的item 
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        
        toolBar.items = items
    }
    
    
    //.MARK:设置输入视图
    private func setTextView() {
        
        view.addSubview(textView)
        
        
        
        //.设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            //.设置高度
            make.height.equalTo(ScreenHeight / 3)
        }
        
        //.添加占位文本
        textView.addSubview(placeholderLabel)
        //.设置约束
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(9)
            make.left.equalTo(textView.snp_left).offset(5)
            
        }
    }
    
    //.MARK: 设置导航条
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        
        //.设置默认 发布 不能与用户交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        
        
        //.设置导航条的 文案
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        //        myView.backgroundColor = UIColor.redColor()
        navigationItem.titleView = myView
        
        
        let titleLable = UIFactory.labelFactory(UIColor.darkGrayColor(), fontSize: 16, text: "发布微博")
        myView.addSubview(titleLable)
        
        let nameLable = UIFactory.labelFactory(UIColor.lightGrayColor(), fontSize: 13, text: UserAccount.shareAccout.name ?? "")
        myView.addSubview(nameLable)
        
        //.添加约束
        titleLable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(myView.snp_top).offset(6)
            make.centerX.equalTo(myView.snp_centerX)
        }
        
        nameLable.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(myView.snp_bottom)
            make.centerX.equalTo(myView.snp_centerX)
        }
    }

}
